#include "msgproc.h"
#include "serialbuffer.h"
#include "protocols.h"
#include "global.h"

MsgProc::MsgProc(QObject *parent) :
    QObject(parent)
{
}

void MsgProc::aplDataCame()
{
    while( aplRecvBuffer::Instance()->getBuffer().isEmpty() == false)
    {
        print(aplRecvBuffer::Instance()->getBuffer().first());
        aplRecvBuffer::Instance()->getBuffer().removeFirst();
        QByteArray sig_msg(3,255);
        emit sig_sendMsg(sig_msg);
    }

    while( aplRecvBuffer::Instance()->getBuffer().isEmpty() == false)
    {
        //取出一帧应用层数据帧
        QByteArray a_msg = aplRecvBuffer::Instance()->getBuffer().first();
        //从缓冲去内移除该帧数据
        aplRecvBuffer::Instance()->getBuffer().removeFirst();
        //消息解析
        msg_processer(a_msg);
    }
}

void MsgProc::msg_processer(QByteArray &msg)
{
    unsigned char TI = msg[0];
    unsigned char src_addr = msg[1];
    unsigned char des_addr = msg[2];
    unsigned char data_len = msg[3];
    unsigned char msg_type = msg[5];

    if( address_verify(src_addr,des_addr) == false )
    {
        qDebug()<<"address isn't correct!";
        return;
    }

    switch( TI )
    {
    case TI_SOH:
        if(msg_type==MSG_FIRE)//火警
        {

        }
        else if(msg_type==MSG_FEDBACK)
        {
        }
        else if(msg_type==MSG_FAULT)
        {
        }
        break;

    case TI_BCSOH:
        break;

    default:
        break;
    }

}



bool MsgProc::address_verify(unsigned char src_addr, unsigned char des_addr)
{
    if(  des_addr==BROADCAST_ADDR )
    {
        return true;
    }

    if( src_addr==host_addr && des_addr==local_addr )
    {
        return true;
    }
    else
    {
        return false;
    }
}
